package com.ziyun.erp.web.modules.material.controller;

import com.ziyun.erp.common.e.material.MaterialStatusEnum;
import com.ziyun.erp.common.e.material.MaterialUnitEnum;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.common.utils.UploadExcel;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.material.entity.MaterialEntity;
import com.ziyun.erp.modules.material.entity.dto.StoreStockMaterialDto;
import com.ziyun.erp.modules.material.entity.storeStockMaterialEntity;
import com.ziyun.erp.modules.material.service.ErpStockService;
import com.ziyun.erp.modules.material.service.MaterialService;
import com.ziyun.erp.modules.material.service.StoreStockMaterialService;
import com.ziyun.erp.modules.supp.entity.SellerInfoEntity;
import com.ziyun.erp.modules.supp.service.SellerInfoService;
import com.ziyun.erp.web.modules.capital.controller.QueryPage;
import io.renren.common.exception.RRExceptionHandler;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;


/**
 * 原料耗材库
 *
 * @author guizhao
 * @email ...
 * @date 2018-08-08 11:23:33
 */
@RestController
@RequestMapping("material/material")
public class MaterialController {


    @Autowired
    private MaterialService materialService;

    @Autowired
    private StoreStockMaterialService storeStockMaterialService;

    @Autowired
    private SellerInfoService sellerInfoService;


    @Autowired
    private ErpStockService erpStockService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("material:material:list")
    public R list(@RequestParam Map<String, Object> params) {

        PageUtils page = materialService.queryPage(params);

        R rs = R.ok();
        rs.put("page", page);

        //存放枚举类到userdata
        Map<String, List> mapEnum = new HashMap<>();
        mapEnum.put("materialUnitEnum", JsonUtils.enumToList(MaterialUnitEnum.class));
        mapEnum.put("materialStatusEnum", JsonUtils.enumToList(MaterialStatusEnum.class));
        rs.put("userData", mapEnum);
        return rs;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{materialId}")
    @RequiresPermissions("material:material:info")
    public R info(@PathVariable("materialId") Integer materialId) {
        MaterialEntity material = materialService.selectById(materialId);

        // 查询所有门店的对应单价
        List<SellerInfoEntity> sellerInfoEntities = storeStockMaterialService.selectCostByMaterialId(materialId);

        return R.ok().put("material", material).put("sellerInfoEntities",sellerInfoEntities);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("material:material:save")
    public R save(@RequestBody StoreStockMaterialDto storeStockMaterialDto) throws Exception{
        storeStockMaterialDto.getMaterialEntity().setCreateName(""+ UserUtils.getCurentUser().getUserId());
        // 获取父级ID
        int ParentID = materialService.getparentId(storeStockMaterialDto.getMaterialEntity().getCategoryId());
        String materialCode = materialService.CreateMaterialCode(ParentID, storeStockMaterialDto.getMaterialEntity().getCategoryId());
        storeStockMaterialDto.getMaterialEntity().setMaterialCode(materialCode);
        materialService.saveMaterialAndStoreStockMaterial(storeStockMaterialDto);
        return R.ok();
    }

    /**
     * @author   Alix_zw
     * @Date
     * @Description   获取门店信息
     
     * @Return    
    **/
    @RequestMapping("/selectSellerName")
    public R getSellerName(){
        List<SellerInfoEntity> selectLists = sellerInfoService.getSelectList();
        Map<String,Object> userData = new HashMap<>();
        userData.put("selectLists",selectLists);
        return R.ok().put("userData",userData);
    }


    /**
     * 修改 material/material/update
     */
    @RequestMapping("/update")
    @RequiresPermissions("material:material:update")
    public R update(@RequestBody StoreStockMaterialDto storeStockMaterialDto) {
        MaterialEntity material = storeStockMaterialDto.getMaterialEntity();
        R r = storeStockMaterialService.saveOrInsert(material, storeStockMaterialDto.getSellerInfoEntity());
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("material:material:delete")
    public R delete(@RequestBody Integer materialId) {
        //todo 删除前判断上架商品是否含有要删除物料，如果有，则不允许删除

        materialService.deleteUpdateById(materialId, UserUtils.getCurentUser().getUserId());
        return R.ok();
    }

    /**
     * 审核
     */
    @RequestMapping("/audit")
    @RequiresPermissions("material:material:update")
    public R audit(@RequestBody Integer materialId) {
        materialService.auditById(materialId);
        return R.ok();
    }

    /**
     * 列表
     */
    @RequestMapping("/queryMaterialsList")
    public R queryMaterialsList(@RequestBody QueryPage<MaterialEntity> query) {
        materialService.queryMaterialsListPage(query.getPage(), query.getParams());
        return R.ok().put("page", query.getPage());
    }


    /**
     * @author Alix_zw
     * @Date
     * @Description 生成Material_Code  (耗材编号)
     * @Return
     **//*

    @RequestMapping("material/queryMaterialsList/getMaterialCode")
    public R getMaterialCode() {

        return R.ok();
    }*/

    /**
     * @author Alix_zw
     * @Date
     * @Description 导入Excel 上传数据
     * @Return
     **/
    @RequestMapping("SellerName/upload")
    public R Excel(HttpServletRequest request ,MultipartFile file){

        if(file != null){
            List<storeStockMaterialEntity> store = null;
            try {
                InputStream inputStream = file.getInputStream();
                store = UploadExcel.readExcel(inputStream);
            } catch (Exception e) {
                e.printStackTrace();
                return R.error("除了Remark,其它字段不能为空");
            }
            for(storeStockMaterialEntity sm : store ){
                int stockId = sm.getStockId();
                String materialId = sm.getMaterialId();
                BigDecimal materialQuantity = sm.getMaterialQuantity();
                BigDecimal cost = sm.getCost();
                BigDecimal money = sm.getMoney();
                String unit = sm.getUnit();
                String remark = sm.getRemark();
                if(remark == null){
                    remark = "Excel 导入";
                }
                int insert = storeStockMaterialService.insert(stockId, materialId, materialQuantity, cost, money, unit, remark);
                if(insert != 1){
                    return R.error("插入数据失败");
                }
            }
        }
        return R.ok("导入成功");
    }
}


